/*
* @(#)LocationPathTag.java
*
* Copyright (c) 2003 DCIVision Ltd
* All rights reserved.
*
* This software is the confidential and proprietary information of DCIVision
* Ltd ("Confidential Information").  You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the license
* agreement you entered into with DCIVision Ltd.
 */

package com.dcivision.dms.taglib;

import java.sql.Connection;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;

/**
  <p>Class Name:    LocationPathTag.java    </p>
  <p>Description:   This tag is the layout the document location

  <p>Modification in "dms.tld"<br>
  <pre>
     [FROM]
     &lt;tagclass&gt;javax.servlet.jsp.tagxt.BodyTagSupport&lt;/tagclass&gt;
     [TO]
     &lt;tagclass&gt;com.dcivision.dms.taglib.layout.LocationPathTag&lt;/tagclass&gt;

     [ADDED]
     &lt;attribute&gt;
     &lt;name&gt;parentID&lt;/name&gt;
     &lt;required&gt;true&lt;/required&gt;
     &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;
     &lt;/attribute&gt;
     &lt;attribute&gt;
     &lt;name&gt;rootID&lt;/name&gt;
     &lt;required&gt;true&lt;/required&gt;
     &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;
     &lt;/attribute&gt;
     &lt;attribute&gt;
     &lt;name&gt;permission&lt;/name&gt;
     &lt;required&gt;true&lt;/required&gt;
     &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;
     &lt;/attribute&gt;
     &lt;attribute&gt;
     &lt;name&gt;rootDocument&lt;/name&gt;
     &lt;required&gt;true&lt;/required&gt;
     &lt;rtexprvalue&gt;true&lt;/rtexprvalue&gt;
     &lt;/attribute&gt;
  </pre>
  </p>

  <p>USAGE:</p>
  <p>The following example shows how to show the customized page title using pass in String array</p>
  <p><code>&lt;dms:locationPath/&gt; parentID='ParentID'</strong> <strong>rootID='RootID'</strong></p>
  <p><strong> permission='PermissionStr'</strong> <strong>rootDocument='RootDocument'</strong> &gt;</code></p>

 * @author           Zoe Shum
 * @company          DCIVision Limited
 * @creation date    08/08/2003
 * @version          $Revision: 1.36.2.4 $
 */

public class LocationPathTag extends BodyTagSupport {

  public static final String REVISION = "$Revision: 1.36.2.4 $";

  private static final Log log = LogFactory.getLog(LocationPathTag.class);

  int iscreenSize = -1;
  int idefaultLength ;
  int isize640 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_640).intValue();
  int isize800 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_800).intValue();
  int isize1024 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_1024).intValue();
  int isize1152 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_1152).intValue();
  int isize1280 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_1280).intValue();
  int isize1281 = SystemParameterFactory.getSystemParameterInteger(SystemParameterConstant.DMS_MAX_WORDS_OF_TITLE_BY_SCREEN_WIDTH_1281).intValue();

  private Integer sParentID;
  private Integer sRootID;
  private String sPermission=null;
  private DmsDocument rootDocument=null;
  private boolean bOnClick = true;
  public static final String FILE_SEPARATOR = "\\";
  private boolean bShowIndexFlag = true;
  private int limitLength = -1;
  private String indexFlag="showIndexFlag";
  private boolean bShowAllPath = true;
  private String sReturnTo = "";
  private String sRturnTop = "";

  /**
   * Constructor
   */
  public int getDefaultValue() {
        this.iscreenSize = TextUtility.parseInteger(this.pageContext.getSession().getAttribute(GlobalConstant.CLIENT_SCREEN_WIDTH_KEY).toString() );

        if (iscreenSize <= 640) {
                idefaultLength = isize640;
        } else if(iscreenSize <= 800 && iscreenSize >640 ) {
                idefaultLength = isize800;
        } else if(iscreenSize <= 1024 && iscreenSize >800 ) {
                idefaultLength = isize1024;
        } else if(iscreenSize <= 1152 && iscreenSize >1024 ) {
                idefaultLength = isize1152;
        } else if(iscreenSize <= 1280 && iscreenSize >1152 ) {
                idefaultLength = isize1280;
        } else {
                idefaultLength = isize1281;
        }
        return idefaultLength;
  }

  public void setReturnTo(String sReturnTo){
    this.sReturnTo = sReturnTo;
  }

  public String getReturnTo(){
    return this.sReturnTo;
  }

  public void setReturnTop(String sReturnTop){
    this.sRturnTop = sReturnTop;
  }

  public String getReturnTop(){
    return this.sRturnTop;
  }

  public void setShowAllPath(boolean bShowAllPath){
    this.bShowAllPath = bShowAllPath;
  }

  public boolean getShowAllPath() {
    return this.bShowAllPath;
  }

  public void setShowIndexFlag(boolean indexFlag){
    this.bShowIndexFlag = indexFlag;
  }

  public boolean getShowIndexFlag() {
    return this.bShowIndexFlag;
  }

  public void setIndexFlag(String indexFlag) {
    this.indexFlag = indexFlag;
  }

  public String getIndexFlag() {
    return this.indexFlag;
  }

  public LocationPathTag() {
    super();
  }

  public Integer getParentID() {
    return this.sParentID;
  }

  public void setParentID(Integer sParentID) {
    this.sParentID = sParentID;
  }

  public Integer getRootID() {
    return this.sRootID;
  }

  public void setPermission(String permission){
    this.sPermission = permission;
  }

  public String getPermission(){
    return this.sPermission;
  }

  public void setRootDocument(DmsDocument rootDoc){
    this.rootDocument = rootDoc;
  }

  public DmsDocument getRootDocument(){
    return this.rootDocument;
  }

  public void setRootID(Integer sRootID) {
    this.sRootID = sRootID;
  }

  public boolean getOnClick(){
    return this.bOnClick;
  }

  public void setOnClick(boolean onClick){
    this.bOnClick = onClick;
  }

  public int getLimitLength() {
     return (this.limitLength);
  }

  public void setLimitLength(int limitLength) {
        this.limitLength = limitLength;
  }

  public int doStartTag() throws JspException {
     if (sParentID == null) {
       throw new JspTagException("LocationPathTag: no header String defined");
     }
     try {
       pageContext.getOut().print(this.src());
       return(SKIP_BODY);
     } catch (Exception e) {
       log.error(e, e);
       throw new JspException(e);
     }
   }

   public int doEndTag() throws JspException {
     return EVAL_PAGE;
  }

  protected String src() throws javax.servlet.jsp.JspException {

    limitLength = getDefaultValue();

    SessionContainer sessionContainer = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    Connection conn = (Connection)pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
    String contextPath = (String)this.pageContext.getServletContext().getAttribute(GlobalConstant.CONTEXT_PATH_KEY);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);

    StringBuffer buffer = new StringBuffer();
    String path="";
    try {
      if (bShowAllPath) {
        do {
          DmsDocument doc = docRetrievalManager.getDocument(sParentID);
//          DmsDocument documentRoot = docRetrievalManager.getRootFolderByRootID(((DmsDocument) doc).getRootID());
//          String permission = (String) permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_DOCUMENT, documentRoot.getID());

          if (rootDocument==null) {
            buffer.insert(0, GlobalConstant.EMPTY_FIELD);
            break;
          }
          /*
           * joan.xiong update code for bug EIP-938 by 2006/11/22
           */
          if(Utility.isEmpty(doc)){
            return "-";
          }else{
          /*
           * joan.xiong update code end
           */
              if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(rootDocument.getDocumentName())){
                  //For Personal Folder
                  String name = doc.getDocumentName();
                  if (rootDocument.getOwnerID().intValue() != sessionContainer.getUserRecordID().intValue()){
                    // update by beyond for EIP-1951
                    name = doc.getDocumentName();
                    // end update for EIP-1951

                    //for personal folder, show the folder's owner. update by wiflish.xie for EIP-2118
                    if(DmsOperationConstant.DMS_PERSONAL_ROOT.equals(name)) {
                      name = UserInfoFactory.getUserFullName(rootDocument.getOwnerID()) + "'s " + name;
                    }

                    buffer.insert(0, name);
                  }else{
                    if (!bOnClick) {
                      buffer.insert(0, name);
                    } else {
                      if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())){
                        String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=" + (Utility.isEmpty(this.getReturnTo())?"":("&returnTo=" + this.getReturnTo())) + (Utility.isEmpty(this.getReturnTop())?"":("&returnTop=" + this.getReturnTop()));
                        buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" " +
                      " onmouseover=\"return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(sParentID)) + "');\" onmouseout=\"return nd();\"/>" + name + "</a>");
                      }
                      else {
                        buffer.insert(0, name);
                      }
                    }
                  }
                } else {
                  //For Public Folder
                  if  (sPermission.indexOf("R")>=0) {
                    if (!bOnClick) {
                      buffer.insert(0, doc.getDocumentName());
                    } else {
                      if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                        String url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER +"&sortAttribute=" + (Utility.isEmpty(this.getReturnTo())?"":("&returnTo=" + this.getReturnTo())) + (Utility.isEmpty(this.getReturnTop())?"":("&returnTop=" + this.getReturnTop()));
                        buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" " +
                      " onmouseover=\"return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(sParentID)) + "');\" onmouseout=\"return nd();\"/>" + doc.getDocumentName() + "</a>");
                      } else {
                        buffer.insert(0, doc.getDocumentName());
                      }
                    }
                  } else {
                    buffer.insert(0, doc.getDocumentName());
                  }
                }
                buffer.insert(0, FILE_SEPARATOR);
                sParentID = doc.getParentID();
          }//joan.xiong update code for bug EIP-938 by 2006/11/22
        } while (sParentID.intValue()!=0);

        path = buffer.toString();
        if (path.length() > 0) {
          path = path.substring(1);
        }
      } else {
        DmsDocument doc = docRetrievalManager.getDocument(sParentID);
        /*
         * joan.xiong update code for bug EIP-938 by 2006/11/22
         */
        if(Utility.isEmpty(doc)){
          return "-";
        }else{
        /*
         * joan.xiong update code end
         */
            String name = docRetrievalManager.getLocationPath(sParentID);

            if (name.length() > this.limitLength) {
              name = name.substring(0,this.limitLength).replaceAll(" ", "&nbsp;")+"...";
            }

            if (rootDocument != null && DmsOperationConstant.DMS_PERSONAL_ROOT.equals(rootDocument.getDocumentName())) {
              //For Personal Folder
              if (rootDocument.getOwnerID().intValue() != sessionContainer.getUserRecordID().intValue()) {
                if(docRetrievalManager.getLocationPath(sParentID).length() > this.limitLength ) {
                  name = docRetrievalManager.getLocationPath(sParentID).substring(0,this.limitLength).replaceAll(" ", "&nbsp;")+"...";
                }
                buffer.insert(0, name);
              } else {
                if (!bOnClick) {
                buffer.insert(0, name);
                } else {
                  if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                    String url = contextPath + "/dms/ListDmsDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PERSONAL_FOLDER + "&sortAttribute=" + (Utility.isEmpty(this.getReturnTo())?"":("&returnTo=" + this.getReturnTo())) + (Utility.isEmpty(this.getReturnTop())?"":("&returnTop=" + this.getReturnTop()));
                      buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" " +
                      " onmouseover=\"return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(sParentID)) + "');\" onmouseout=\"return nd();\">" + name + "</a>");
                  } else {
                    buffer.insert(0, name);
                  }
                }
              }
            } else {
              //For Public Folder
              if  (sPermission.indexOf("R")>=0) {
                if (!bOnClick) {
                  buffer.insert(0, name);
                } else {
                  if (GlobalConstant.RECORD_STATUS_ACTIVE.equals(doc.getRecordStatus())) {
                    String url ="";
                    if("showSystemLogIndexFlag".equals(this.getIndexFlag())||"showRecentlyAccessIndexFlag".equals(this.getIndexFlag())){
                      url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + DmsOperationConstant.LIST_PERSONAL_HOME +"&sortAttribute=" + (Utility.isEmpty(this.getReturnTo())?"":("&returnTo=" + this.getReturnTo())) + (Utility.isEmpty(this.getReturnTop())?"":("&returnTop=" + this.getReturnTop()));
                    }else{
                      url = contextPath + "/dms/ListDmsPublicDocument.do?rootID=" + sRootID + "&parentID=" + sParentID +  "&curFunctionCode=" + SystemFunctionConstant.DMS_PUBLIC_FOLDER +"&sortAttribute=" + (Utility.isEmpty(this.getReturnTo())?"":("&returnTo=" + this.getReturnTo())) + (Utility.isEmpty(this.getReturnTop())?"":("&returnTop=" + this.getReturnTop()));
                    }
                     buffer.insert(0, " <a href=\"javascript://\" onclick=\"return checkWindowForAction('" + url + "');\" " +
                       " onmouseover=\"return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(sParentID)) + "');\" onmouseout=\"return nd();\">" + name + "</a>");
                  } else {
                    buffer.insert(0, name);
                  }
                }
              } else {
                buffer.insert(0, name);
              }
            }
            buffer.insert(0, FILE_SEPARATOR);

            path = buffer.toString();
            if (path.length() > 0) {
              path = path.substring(1);
            }
            if (path.indexOf("<a href")<0 && path.length() > this.limitLength) {
               path = " <a href=\"javascript://\" onmouseover=\"return getDocumentInfo('" +TextUtility.escapeJSString(docRetrievalManager.getLocationPath(sParentID)) + "');\" onmouseout=\"return nd();\">" + path.substring(0,this.limitLength).replaceAll(" ", "&nbsp;")+"..." + "</a>";
            }
        }//joan.xiong update code for bug EIP-938 by 2006/11/22
      }
    } catch (ApplicationException appEx) {
      throw new JspException(appEx);
    }

    return path;
  }

  public void release() {
    super.release();
    sParentID = null;
  }
}